package com.guldan.jaina.manager;

import com.guldan.core.constants.CommonConstant;
import com.guldan.core.enums.AuditorTypeEn;
import com.guldan.core.enums.ProjectRegisterBatchEn;
import com.guldan.core.enums.ProjectRegisterEn;
import com.guldan.core.manager.BaseManager;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.dicType.DicTypeDTO;
import com.guldan.jaina.dto.orgbatchsummary.OrgBatchSummaryDTO;
import com.guldan.jaina.dto.orgbatchsummary.OrgBatchSummarySearchDTO;
import com.guldan.jaina.dto.paysummary.PaySummaryDTO;
import com.guldan.jaina.dto.projectregisterbatch.BatchAuditorDTO;
import com.guldan.jaina.dto.registerbatchstatics.ProjectBatchExtStatDTO;
import com.guldan.jaina.dto.registersuccess.RegisterSuccessDTO;
import com.guldan.jaina.dto.registersuccess.RegisterSuccessSearchDTO;
import com.guldan.jaina.dto.summarybatchrelation.SummaryBatchRelationDTO;
import com.guldan.jaina.utils.DicTypeDomainConvertUtils;
import com.guldan.jaina.utils.OrgBatchSummaryDomainConvertUtils;
import com.guldan.jaina.utils.PaySummaryDomainConvertUtils;
import com.guldan.jaina.utils.UserUtils;
import com.guldan.mapper.db.dto.ProjectBatchStatDTO;
import com.guldan.mapper.db.dto.orgBatchSummary.OrgBatchSummaryExtDTO;
import com.guldan.mapper.db.entity.*;
import com.guldan.mapper.db.mapper.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Silas.
 * Date: 2016/12/5
 * Time: 22:24
 */
@Service
public class OrgBatchSummaryManager extends BaseManager {

    @Autowired
    private OrgBatchSummaryMapperExt orgBatchSummaryMapperExt;

    @Autowired
    private SummaryBatchRelationMapperExt summaryBatchRelationMapperExt;

    @Autowired
    private RegisterSuccessMapperExt registerSuccessMapperExt;

    @Autowired
    private ProjectRegisterBatchMapperExt projectRegisterBatchMapperExt;

    @Autowired
    private RegisterBatchStaticsMapperExt registerBatchStaticsMapperExt;

    @Autowired
    private ProjectMapperExt projectMapperExt;

    @Autowired
    private ProjectRegisterBatchManager projectRegisterBatchManager;

    @Autowired
    private AreaMapperExt areaMapperExt;

    //主管部门上报汇总后，汇总批次记录
    public Pagination<OrgBatchSummaryDTO> orgBatchSummaryList(OrgBatchSummarySearchDTO searchDTO) {

        List<Integer> state = new ArrayList<>();

        if (searchDTO.getState() != null && searchDTO.getState().size() > 0) {
            state = searchDTO.getState();
        } else {
            state.add(ProjectRegisterBatchEn.finance_auditor_ing.getCode());
            state.add(ProjectRegisterBatchEn.finance_auditor_ed.getCode());
            state.add(ProjectRegisterBatchEn.finance_created_file.getCode());
            state.add(ProjectRegisterBatchEn.finance_downloaded_file.getCode());
            state.add(ProjectRegisterBatchEn.bank_success_all.getCode());
            state.add(ProjectRegisterBatchEn.bank_fail_all.getCode());
            state.add(ProjectRegisterBatchEn.bank_success_part.getCode());
        }
        searchDTO.setState(state);
        searchDTO.setOrgCode(UserUtils.getUser().getWorkOrg());

        return orgSummaryList(searchDTO);
    }

    //添加新的汇总批次
    public OrgBatchSummaryDTO save(OrgBatchSummaryDTO dto, List<Integer> batchIds) {

        //先查询是否已经存在该批次
        OrgBatchSummary entity = orgBatchSummaryMapperExt.selectByPrimaryKey(dto.getSummaryId());
        if (entity == null) {
            //已经存在
            entity = new OrgBatchSummary();
            entity.setSummaryId(dto.getSummaryId());
            entity.setAreaId(dto.getAreaId());
            entity.setOrgId(dto.getOrgId());
            entity.setProjectId(dto.getProjectId());
            entity.setYear(dto.getYear());
            entity.setPayCycleCode(dto.getPayCycleCode());
            entity.setTotalCount(dto.getTotalCount());
            entity.setFinanceSuccessCount(dto.getFinanceSuccessCount());
            entity.setFinanceFailCount(dto.getFinanceFailCount());
            entity.setTotalMoney(dto.getTotalMoney());
            entity.setSuccessMoney(dto.getSuccessMoney());
            entity.setFailMoney(dto.getFailMoney());
            entity.setState(dto.getState());
            entity.setSubsidyCount(dto.getSubsidyCount());

            entity.setCreateTime(DateUtil.getCurrentTime());
            entity.setModifyTime(DateUtil.getCurrentTime());

            orgBatchSummaryMapperExt.insertSelective(entity);
        }

        //开始写入关联表
        if (batchIds != null && batchIds.size() > 0) {
            //先进行删除
            SummaryBatchRelationExample example = new SummaryBatchRelationExample();
            SummaryBatchRelationExample.Criteria criteria = example.createCriteria();
            criteria.andSummaryIdEqualTo(entity.getSummaryId());
            criteria.andBatchIdIn(batchIds);
            summaryBatchRelationMapperExt.deleteByExample(example);

            //进行添加
            for (Integer batchId : batchIds) {
                SummaryBatchRelation e = new SummaryBatchRelation();
                e.setSummaryId(entity.getSummaryId());
                e.setBatchId(batchId);
                e.setCreateTime(DateUtil.getCurrentTime());
                summaryBatchRelationMapperExt.insertSelective(e);
            }
        }

        //修改登记成功记录表记录
        //先将现有summaryId下的所有人员的的summary_id置空
        RegisterSuccess update = new RegisterSuccess();
        update.setSummaryId("");

        RegisterSuccessExample example = new RegisterSuccessExample();
        RegisterSuccessExample.Criteria criteria = example.createCriteria();
        criteria.andSummaryIdEqualTo(entity.getSummaryId());

        registerSuccessMapperExt.updateByExampleSelective(update, example);

        //再将新的summaryId写入，将批次列表下的所有人都改成该summary_id下记录
        update = new RegisterSuccess();
        update.setSummaryId(entity.getSummaryId());
        example = new RegisterSuccessExample();
        criteria = example.createCriteria();
        criteria.andBatchIdIn(batchIds);

        registerSuccessMapperExt.updateByExampleSelective(update, example);

        dto = OrgBatchSummaryDomainConvertUtils.convert(entity);
        return dto;
    }

    //根据批次ids对批次进行汇总查询;主管部门汇总上报，查询汇总记录
    public List<OrgBatchSummaryExtDTO> collectBatchIdForOrgSubmit(List<Integer> batchIds) {
        return orgBatchSummaryMapperExt.collectBatchIdForOrgSubmit(ProjectRegisterBatchEn.org_auditor_ed.getCode(), batchIds);
    }


    //查询汇总批次记录
    public Pagination<OrgBatchSummaryDTO> list(OrgBatchSummarySearchDTO searchDTO) {
        Pagination<OrgBatchSummaryDTO> result = new Pagination<>(searchDTO.getCurrentPage(), searchDTO.getPerPage());
        OrgBatchSummaryExample example = buildSearchExample(searchDTO);
        int total = orgBatchSummaryMapperExt.countByExample(example);
        result.setTotalCount(total);
        if (total > 0) {
            List<OrgBatchSummaryDTO> data = new ArrayList<>();
            List<OrgBatchSummary> list = orgBatchSummaryMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());

            data = getDTOList(list);

            result.setList(data);
        }
        return result;
    }

    //主管部门，查询汇总批次记录
    public Pagination<OrgBatchSummaryDTO> orgSummaryList(OrgBatchSummarySearchDTO searchDTO) {
        Pagination<OrgBatchSummaryDTO> result = new Pagination<>(searchDTO.getCurrentPage(), searchDTO.getPerPage());

        List<Integer> areaIds = new ArrayList<>();
        if (searchDTO.getAreaId() != null && searchDTO.getAreaId() > 0) {
            areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, searchDTO.getAreaId()));
            areaIds.add(searchDTO.getAreaId());
        } else {
            areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, UserUtils.getUser().getAreaId()));
            areaIds.add(UserUtils.getUser().getAreaId());
        }

        int total = orgBatchSummaryMapperExt.orgSelectSummaryBatchListCount(searchDTO.getOrgCode(), searchDTO.getState(), areaIds, searchDTO.getProjectId() == null ? 0 : searchDTO.getProjectId(), searchDTO.getYear() == null ? 0 : searchDTO.getYear(), searchDTO.getPayCycleCode() == null ? "" : searchDTO.getPayCycleCode(), searchDTO.getSubsidyCount() == null ? 0 : searchDTO.getSubsidyCount());
        result.setTotalCount(total);
        if (total > 0) {
            List<OrgBatchSummaryDTO> data = new ArrayList<>();
            List<OrgBatchSummary> list = orgBatchSummaryMapperExt.orgSelectSummaryBatchList(searchDTO.getOrgCode(), searchDTO.getState(), areaIds, searchDTO.getProjectId() == null ? 0 : searchDTO.getProjectId(), searchDTO.getYear() == null ? 0 : searchDTO.getYear(), searchDTO.getPayCycleCode() == null ? "" : searchDTO.getPayCycleCode(), searchDTO.getSubsidyCount() == null ? 0 : searchDTO.getSubsidyCount(), result.getOffset(), result.getPageSize());

            data = getDTOList(list);


            result.setList(data);
        }
        return result;
    }

    //财政部门，查询汇总批次记录
    public Pagination<OrgBatchSummaryDTO> financeSummaryList(OrgBatchSummarySearchDTO searchDTO) {
        Pagination<OrgBatchSummaryDTO> result = new Pagination<>(searchDTO.getCurrentPage(), searchDTO.getPerPage());

        List<Integer> areaIds = new ArrayList<>();
        if (searchDTO.getAreaId() != null && searchDTO.getAreaId() > 0) {
            areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, searchDTO.getAreaId()));
            areaIds.add(searchDTO.getAreaId());
        } else {
            areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, UserUtils.getUser().getAreaId()));
            areaIds.add(UserUtils.getUser().getAreaId());
        }

        int total = orgBatchSummaryMapperExt.financeSelectSummaryBatchListCount(searchDTO.getOrgCode(), searchDTO.getState(), areaIds, searchDTO.getProjectId() == null ? 0 : searchDTO.getProjectId(), searchDTO.getYear() == null ? 0 : searchDTO.getYear(), searchDTO.getPayCycleCode() == null ? "" : searchDTO.getPayCycleCode(), searchDTO.getSubsidyCount() == null ? 0 : searchDTO.getSubsidyCount());
        result.setTotalCount(total);
        if (total > 0) {
            List<OrgBatchSummaryDTO> data = new ArrayList<>();
            List<OrgBatchSummary> list = orgBatchSummaryMapperExt.financeSelectSummaryBatchList(searchDTO.getOrgCode(), searchDTO.getState(), areaIds, searchDTO.getProjectId() == null ? 0 : searchDTO.getProjectId(), searchDTO.getYear() == null ? 0 : searchDTO.getYear(), searchDTO.getPayCycleCode() == null ? "" : searchDTO.getPayCycleCode(), searchDTO.getSubsidyCount() == null ? 0 : searchDTO.getSubsidyCount(), result.getOffset(), result.getPageSize());

            data = getDTOList(list);

            result.setList(data);
        }
        return result;
    }


    private List<OrgBatchSummaryDTO> getDTOList(List<OrgBatchSummary> list) {
        List<OrgBatchSummaryDTO> data = new ArrayList<>();
        //List<OrgBatchSummary> list = orgBatchSummaryMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());
        for (OrgBatchSummary entity : list) {

            OrgBatchSummaryDTO dto = OrgBatchSummaryDomainConvertUtils.convert(entity);

            //获取项目名称
            dto.setProjectName(projectMapperExt.selectByPrimaryKey(dto.getProjectId()).getProjectName());

            try {
                dto.setAreaName(areaMapperExt.selectByPrimaryKey(dto.getAreaId()).getAreaName());
            } catch (Exception ex) {
            }

            //获取批次汇总的人数相关统计
            ProjectBatchStatDTO projectBatchStatDTO = projectRegisterBatchManager.getProjectBatchSummaryStatInfo(entity.getSummaryId(), ProjectRegisterEn.getSuccessStateList(), ProjectRegisterEn.getFailStateList());
            dto.setTotalCount(projectBatchStatDTO.getTotalCount());
            dto.setSuccessCount(projectBatchStatDTO.getSuccessCount());
            dto.setFailCount(projectBatchStatDTO.getFailCount());
            dto.setSuccessMoney(projectBatchStatDTO.getSuccessMoney());
            dto.setFailMoney(projectBatchStatDTO.getFailMoney());


            //扩展属性相关统计，比如：金额，面积
            List<Integer> batchIds = selectBatchIdsBySummaryId(entity.getSummaryId());
            List<ProjectBatchStatDTO> projectBatchStatDTOs = registerBatchStaticsMapperExt.statProjectBatchExtData(batchIds, ProjectRegisterEn.getSuccessStateList());
            List<ProjectBatchExtStatDTO> projectBatchExtStatDTOs = new ArrayList<>();
            if (projectBatchStatDTOs != null && projectBatchExtStatDTOs.size() > 0) {
                for (ProjectBatchStatDTO pbsDTO : projectBatchStatDTOs) {

                    ProjectBatchExtStatDTO projectBatchExtStatDTO = new ProjectBatchExtStatDTO();
                    projectBatchExtStatDTO.setBatchId(pbsDTO.getBatchId());
                    projectBatchExtStatDTO.setExtId(pbsDTO.getExtId());
                    projectBatchExtStatDTO.setExtName(pbsDTO.getExtName());
                    projectBatchExtStatDTO.setExtCalculate(pbsDTO.getExtCalculate());

                    projectBatchExtStatDTOs.add(projectBatchExtStatDTO);
                }
            }

            dto.setExtStatList(projectBatchExtStatDTOs);
            data.add(dto);
        }
        return data;
    }


    /*区县财政审批*/
    //+++++++++++++++++++++++++++++++++++++++++++++++
    //财政待审批批次汇总记录
    public Pagination<OrgBatchSummaryDTO> financeAuditorList(OrgBatchSummarySearchDTO searchDTO) {

        List<Integer> state = new ArrayList<>();
        state.add(ProjectRegisterBatchEn.finance_auditor_ing.getCode());
        searchDTO.setState(state);
        searchDTO.setOrgCode(UserUtils.getUser().getWorkOrg());
        return financeSummaryList(searchDTO);
    }

    //对批次汇总记录进行审批，审批通过、审批不通过
    public Boolean financeAuditorApproval(BatchAuditorDTO dto) {
        Boolean ret = true;
        try {

            int newState;
            RegisterSuccess update = new RegisterSuccess();

            ProjectRegisterBatch update2 = new ProjectRegisterBatch();

            if (dto.getAuditorType() == AuditorTypeEn.allow.getCode()) {
                //审批通过
                newState = ProjectRegisterBatchEn.finance_auditor_ed.getCode();
                update.setState(ProjectRegisterEn.finance_auditor_ed.getCode());
                update2.setState(ProjectRegisterBatchEn.finance_auditor_ed.getCode());
            } else {
                //审批不通过
                newState = ProjectRegisterBatchEn.finance_auditor_fail.getCode();
                update.setState(ProjectRegisterEn.finance_auditor_fail.getCode());
                update2.setState(ProjectRegisterBatchEn.org_auditor_ing.getCode());
                update2.setFailReason(dto.getReason());
            }

            //修改批次汇总表记录状态 OrgBatchSummary
            OrgBatchSummary orgBatchSummary = orgBatchSummaryMapperExt.selectByPrimaryKey(dto.getSummaryId());
            orgBatchSummary.setState(newState);
            orgBatchSummary.setModifyTime(DateUtil.getCurrentTime());
            orgBatchSummaryMapperExt.updateByPrimaryKeySelective(orgBatchSummary);

            //修改批次表状态 ProjectRegisterBatch
//            ProjectRegisterBatch projectRegisterBatch = projectRegisterBatchMapperExt.selectByPrimaryKey(dto.getBatchId());
            ProjectRegisterBatchExample update2Example = new ProjectRegisterBatchExample();
            ProjectRegisterBatchExample.Criteria update2Criteria = update2Example.createCriteria();

            update2.setModifyTime(DateUtil.getCurrentTime());

            update2Criteria.andStateEqualTo(ProjectRegisterEn.finance_auditor_ing.getCode());
            update2Criteria.andBatchIdIn(selectBatchIdsBySummaryId(dto.getSummaryId()));
            update2Criteria.andIsDeleteEqualTo(false);

            projectRegisterBatchMapperExt.updateByExampleSelective(update2, update2Example);

            //修改登记记录状态 RegisterSuccess
            RegisterSuccessExample updateExample = new RegisterSuccessExample();
            RegisterSuccessExample.Criteria updateCriteria = updateExample.createCriteria();




            update.setModifyTime(DateUtil.getCurrentTime());
            updateCriteria.andStateEqualTo(ProjectRegisterEn.finance_auditor_ing.getCode());
            updateCriteria.andBatchIdIn(selectBatchIdsBySummaryId(dto.getSummaryId()));
            updateCriteria.andIsDeleteEqualTo(false);
            registerSuccessMapperExt.updateByExampleSelective(update, updateExample);

        } catch (Exception ex) {
            ret = false;
            logger.error(ex.getMessage());
        }
        return ret;
    }


    //财政通过审批的批次汇总列表
    public Pagination<OrgBatchSummaryDTO> financeAuditoredSummaryBatchList(OrgBatchSummarySearchDTO searchDTO) {

        if (searchDTO.getState() == null || searchDTO.getState().size() == 0) {
            searchDTO.setState(ProjectRegisterBatchEn.getFinanceFileMenuList());
        }
        searchDTO.setOrgCode(UserUtils.getUser().getWorkOrg());
        return financeSummaryList(searchDTO);
    }

    //build查询Example
    private OrgBatchSummaryExample buildSearchExample(OrgBatchSummarySearchDTO search) {
        OrgBatchSummaryExample example = new OrgBatchSummaryExample();
        OrgBatchSummaryExample.Criteria criteria = example.createCriteria();

        if (search.getProjectId() != null && search.getProjectId() > 0) {
            criteria.andProjectIdEqualTo(search.getProjectId());
        }
        if (StringUtils.isNotBlank(search.getSummaryId())) {
            criteria.andSummaryIdEqualTo(search.getSummaryId());
        }
        if (search.getState() != null && search.getState().size() > 0) {
            criteria.andStateIn(search.getState());
        }
        if (search.getNotState() != null && search.getNotState().size() >= 0) {
            criteria.andStateNotIn(search.getNotState());
        }
        if (search.getYear() != null && search.getYear() > 0) {
            criteria.andYearEqualTo(search.getYear());
        }
        if (search.getAreaId() != null && search.getAreaId() > 0) {
            criteria.andAreaIdEqualTo(search.getAreaId());
        }

        criteria.andIsDeleteEqualTo(Boolean.FALSE);
        if (StringUtils.isNotBlank(search.getOrderByClause())) {
            example.setOrderByClause(search.getOrderByClause());
        } else {
            example.setOrderByClause("summary_id asc");
        }
        return example;
    }


    //获取某个汇总批次summaryid下关联的批次id列表
    public List<Integer> selectBatchIdsBySummaryId(String summaryId) {

        SummaryBatchRelationExample example = new SummaryBatchRelationExample();
        SummaryBatchRelationExample.Criteria criteria = example.createCriteria();
        criteria.andSummaryIdEqualTo(summaryId);
        criteria.andIsDeleteEqualTo(false);

        List<Integer> batchIds = new ArrayList<>();
        List<SummaryBatchRelation> entityList = summaryBatchRelationMapperExt.selectByExample(example);

        if (entityList != null && entityList.size() > 0) {
            for (SummaryBatchRelation entity : entityList)
                batchIds.add(entity.getBatchId());
        }
        return batchIds;
    }

    public OrgBatchSummaryDTO get(String summaryId) {
        OrgBatchSummaryExample example = new OrgBatchSummaryExample();
        OrgBatchSummaryExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(summaryId)) {
            criteria.andSummaryIdEqualTo(summaryId);
        }
        criteria.andIsDeleteEqualTo(Boolean.FALSE);
        List<OrgBatchSummary> list = orgBatchSummaryMapperExt.selectByExample(example);
        OrgBatchSummaryDTO dto = null;
        if (list != null && list.size() > 0) {
            List<OrgBatchSummaryDTO> dtoList = getDTOList(list);
            dto = dtoList.get(0);
        }
        return dto;
    }

    public OrgBatchSummaryDTO save(OrgBatchSummaryDTO dto) {

        OrgBatchSummary entity;
        if (dto.getSummaryId() != null && !dto.getSummaryId().equals("")) {

            entity = orgBatchSummaryMapperExt.selectByPrimaryKey(dto.getSummaryId());
            entity.setSummaryId(dto.getSummaryId());
            entity.setAreaId(dto.getAreaId());
            entity.setOrgId(dto.getOrgId());
            entity.setProjectId(dto.getProjectId());
            entity.setYear(dto.getYear());
            entity.setPayCycleCode(dto.getPayCycleCode());
            entity.setTotalCount(dto.getTotalCount());
            entity.setFinanceSuccessCount(dto.getFinanceSuccessCount());
            entity.setFinanceFailCount(dto.getFinanceFailCount());
            entity.setTotalMoney(dto.getTotalMoney());
            entity.setSuccessMoney(dto.getSuccessMoney());
            entity.setFailMoney(dto.getFailMoney());
            entity.setState(dto.getState());
            entity.setSubsidyCount(dto.getSubsidyCount());

            entity.setDisabled(dto.getDisabled());
            entity.setModifyTime(DateUtil.getCurrentTime());
            entity.setModifier(dto.getModifier());
            orgBatchSummaryMapperExt.updateByPrimaryKeySelective(entity);
        } else {
            entity = new OrgBatchSummary();
            entity.setAreaId(dto.getAreaId());
            entity.setOrgId(dto.getOrgId());
            entity.setProjectId(dto.getProjectId());
            entity.setYear(dto.getYear());
            entity.setPayCycleCode(dto.getPayCycleCode());
            entity.setTotalCount(dto.getTotalCount());
            entity.setFinanceSuccessCount(dto.getFinanceSuccessCount());
            entity.setFinanceFailCount(dto.getFinanceFailCount());
            entity.setTotalMoney(dto.getTotalMoney());
            entity.setSuccessMoney(dto.getSuccessMoney());
            entity.setFailMoney(dto.getFailMoney());
            entity.setState(dto.getState());
            entity.setSubsidyCount(dto.getSubsidyCount());

            entity.setDisabled(dto.getDisabled());
            entity.setCreator(dto.getModifier());
            entity.setCreateTime(DateUtil.getCurrentTime());
            orgBatchSummaryMapperExt.insertSelective(entity);
        }
        dto = OrgBatchSummaryDomainConvertUtils.convert(entity);
        return dto;
    }

    //删除
    public Boolean delete(String summaryId) {
        OrgBatchSummary entity = orgBatchSummaryMapperExt.selectByPrimaryKey(summaryId);
        entity.setIsDelete(true);
        return orgBatchSummaryMapperExt.updateByPrimaryKeySelective(entity) > 0;
    }

}
